<template>
  <QueryBase @onSearch="doQuery" @onAdd="handleAdd" @on-import="handleImport" :show-import="true">
    <template #search>
      <el-form :inline="true" :model="queryForm">
        <el-form-item :label="t('课程名称')">
          <el-input
            v-model="queryForm.name"
            :placeholder="t('请输入')"
            clearable
            v-enter="doQuery"
          />
        </el-form-item>
        <el-form-item :label="t('课程分类')">
          <el-cascader
            v-model="queryForm.categoryId"
            :placeholder="t('请选择')"
            :options="categoryOptions"
            :props="{
              checkStrictly: false
            }"
            filterable
            clearable
          />
        </el-form-item>
      </el-form>
    </template>
    <el-table :data="tableData" :border="true" header-row-class-name="table-header" height="60vh">
      <el-table-column prop="name" :label="t('名称')" width="220" />
      <el-table-column prop="categoryText" :label="t('分类')" width="220" />
      <el-table-column prop="originImg" :label="t('封面')">
        <template #default="scope">
          <v-image
            :src="scope.row.originImg"
            :style="{ width: '65px', height: '65px' }"
            fit="contain"
            :disabled="true"
          ></v-image>
        </template>
      </el-table-column>
      <el-table-column prop="likes" :label="t('点赞数')"> </el-table-column>
      <el-table-column prop="joins" :label="t('学习人数')"> </el-table-column>
      <el-table-column prop="promoter" :label="t('发起人')"> </el-table-column>
      <el-table-column prop="speaker" :label="t('演讲人')"> </el-table-column>
      <el-table-column prop="speaker" :label="t('状态')">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isEnable">启用</el-tag>
          <el-tag type="warning" v-if="!scope.row.isEnable">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="speaker" :label="t('是否上首页')">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.isHot">是</el-tag>
          <el-tag type="warning" v-if="!scope.row.isHot">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('操作')" width="300">
        <template #default="scope">
          <div style="display: flex" v-if="action('edit')">
            <el-button type="text" @click="handleActive(scope.row)" v-if="!scope.row.isEnable"
              >启用</el-button
            >
            <el-button type="text" @click="handleDeactive(scope.row)" v-if="scope.row.isEnable"
              >停用</el-button
            >
            <el-button type="text" @click="handleHot(scope.row)" v-if="!scope.row.isHot"
              >推荐首页</el-button
            >
            <el-button type="text" @click="handleDehot(scope.row)" v-if="scope.row.isHot"
              >撤销首页</el-button
            >
            <el-button type="text" @click="handleModify(scope.row)">修改</el-button>
            <el-button type="text" @click="handleComments(scope.row)">评论管理</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="course-result-pn">
      <VPageNavigation
        :total="total"
        @on-size-changed="handleSizeChange"
        @on-page-changed="handleCurrentChange"
      >
      </VPageNavigation>
    </div>
  </QueryBase>
  <CourseEditor
    @onSubmited="
      (data) => {
        doQuery()
      }
    "
    v-model:show="showEditor"
    :mode="mode"
    :data="editModel"
  >
  </CourseEditor>
  <CourseComments v-model:show="showComments" :courseId="courseId"></CourseComments>
  <el-dialog
    v-model="dialogImportVisible"
    title="导入"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="true"
    :draggable="true"
    @before-close="() => false"
    append-to-body
    style="width: 50%"
  >
    <el-upload
      ref="importUpload"
      class="upload-demo"
      drag
      multiple
      accept=".xls, .xlsx"
      :limit="1"
      :action="uploadAction"
      :auto-upload="false"
      :on-change="onFileChange"
    >
      <el-icon :size="45">
        <UploadFilled />
      </el-icon>
      <div class="el-upload__text">
        {{ t('点击或拖入文件上传') }}
      </div>
    </el-upload>
  </el-dialog>
</template>
<script setup lang="ts">
import { Ref, onMounted, reactive, ref, watch } from 'vue'
import { t } from '@/common/locale'
import {
  activeCourse,
  deactiveCourse,
  doImport,
  queryList,
  hotCourse,
  dehotCourse
} from '@/api/course'
import { getCategoryMap, getCategoryOptions } from '@/api/category'
import elHelper from '@/common/elHelper'
import CourseEditor from '@/components/course/CourseEditor.vue'
import VPageNavigation from '@/components/other/VPageNavigation.vue'
import QueryBase from '@/components/layout/QueryBase.vue'
import CourseComments from '@/components/course/CourseComments.vue'
import comFunc from '@/common/comFunc'
import { action } from '@/common/actionHelper'
import { UploadFilled } from '@element-plus/icons-vue'

const queryForm: CourseQueryForm = reactive({
  name: '',
  categoryId: []
})
const page = ref(1)
const pageSize = ref(0)
const tableData: Ref<CourseDataModel[]> = ref([])
const total = ref(0)
const mode = ref('add')
const editModel: CourseDataModel = reactive({})
const showEditor = ref(false)
const showComments = ref(false)
const courseId = ref('')
const categoryOptions: Ref<CategorySelectOption[]> = ref([])
const dialogImportVisible = ref(false)
const uploadAction = ref(``)
const importUpload = ref()

const doQuery = async () => {
  if (!action('view')) {
    elHelper.showErrorMsg('权限不足')
    return
  }
  const loading = elHelper.showLoading()
  let arr = queryForm.categoryId as string[]
  const categoryId = arr[arr.length - 1]
  const re = await queryList({
    name: queryForm.name,
    categoryId: categoryId,
    pageSize: pageSize.value,
    to: page.value
  })
  if (re.isSuccess) {
    let list = re.data || []
    const map = await getCategoryMap('COURSE')
    list.forEach((item) => {
      const opt = map.get(item.categoryId)
      item.categoryText = opt ? opt : ''
    })
    tableData.value = list
    total.value = re.totalRow || 0
    page.value = re.pageNum || 1
  } else {
    elHelper.showErrorMsg(re.msg)
  }
  elHelper.closeLoading(loading)
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  doQuery()
}
const handleCurrentChange = (val: number) => {
  page.value = val
  doQuery()
}
const handleAdd = () => {
  editModel.categoryId = ''
  editModel.description = ''
  editModel.objectId = ''
  editModel.name = ''
  editModel.originImg = ''
  editModel.thumbImg = ''
  editModel.videoId = ''
  editModel.speaker = ''
  mode.value = 'add'
  showEditor.value = true
}
const handleModify = (data: CourseDataModel) => {
  Object.assign(editModel, data)
  mode.value = 'modify'
  showEditor.value = true
}
const handleComments = (data: CourseDataModel) => {
  courseId.value = comFunc.nvl(data.objectId)
  showComments.value = true
}
const handleActive = async (data: CourseDataModel) => {
  const re = await activeCourse(comFunc.nvl(data.objectId))
  if (re.isSuccess) {
    elHelper.showSuccessMsg('操作成功')
    doQuery()
  } else {
    elHelper.showErrorMsg(re.msg)
  }
}
const handleDeactive = async (data: CourseDataModel) => {
  const re = await deactiveCourse(comFunc.nvl(data.objectId))
  if (re.isSuccess) {
    elHelper.showSuccessMsg('操作成功')
    doQuery()
  } else {
    elHelper.showErrorMsg(re.msg)
  }
}
const handleHot = async (data: CourseDataModel) => {
  const re = await hotCourse(comFunc.nvl(data.objectId))
  if (re.isSuccess) {
    elHelper.showSuccessMsg('操作成功')
    doQuery()
  } else {
    elHelper.showErrorMsg(re.msg)
  }
}
const handleDehot = async (data: CourseDataModel) => {
  const re = await dehotCourse(comFunc.nvl(data.objectId))
  if (re.isSuccess) {
    elHelper.showSuccessMsg('操作成功')
    doQuery()
  } else {
    elHelper.showErrorMsg(re.msg)
  }
}
const handleImport = () => {
  dialogImportVisible.value = true
}
const onFileChange = async (uploadFile) => {
  console.log(uploadFile)
  const re = await doImport(uploadFile.raw)
  if (re.isSuccess) {
    elHelper.showSuccessMsg(re.msg)
    dialogImportVisible.value = false
    doQuery()
    importUpload.value.clearFiles()
  } else {
    elHelper.showErrorMsg(re.msg)
  }
}
onMounted(async () => {
  const l = await getCategoryOptions('COURSE')
  categoryOptions.value = l
  doQuery()
})
</script>
<style scoped lang="scss">
.course-result-pn {
  padding-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
